﻿using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class ManifestResourceRule : ILRule<ManifestResourceHandle>
    {
        [ILInfo]
        public ManifestResourceAttributes Attributes { get; }

        [ILInfo(true)]
        public string Name { get; }

        [ILInfo(true)]
        public EntityHandle Implementation { get; }

        [ILInfo(true)]
        public uint Offset { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public ManifestResourceRule(
            ManifestResourceAttributes attributes,
            string name,
            EntityHandle implementation,
            uint offset)
            : base()
        {
            Attributes = attributes;
            Name = name;
            Implementation = implementation;
            Offset = offset;
        }

        public ManifestResourceRule(MetadataReader reader, ManifestResourceHandle manifestResourceHandle)
            : base(reader)
        {
            ManifestResource manifestResource = reader.GetManifestResource(manifestResourceHandle);
            Attributes = manifestResource.Attributes;
            Name = reader.GetString(manifestResource.Name);
            Implementation = manifestResource.Implementation;
            Offset = (uint)manifestResource.Offset;
            CustomAttributes = manifestResource.GetCustomAttributes();
        }

        public override ManifestResourceHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddManifestResource(
                attributes: Attributes,
                name: Name == null ? default : builder.GetOrAddString(Name),
                implementation: Implementation,
                offset: Offset);
        }
    }
}